import type { Ref } from "vue";
import { nextTick, ref } from "vue";
import type { ScrollbarInstance } from "element-plus";

interface ScrollReturn {
  scrollRef: Ref<ScrollbarInstance | undefined>;
  scrollToBottom: () => Promise<void>;
  scrollTop: () => Promise<void>;
  scrollToBottomIfAtBottom: () => Promise<void>;
}

export function useScroll(): ScrollReturn {
  const scrollRef = ref<ScrollbarInstance>();
  const scrollToBottom = async () => {
    await nextTick();
    if (scrollRef.value) {
      scrollRef.value.setScrollTop(scrollRef.value?.wrapRef?.scrollHeight || 0);
    }
  };

  const scrollTop = async () => {
    await nextTick();
    if (scrollRef.value) {
      scrollRef.value.setScrollTop(0);
    }
  };
  const scrollToBottomIfAtBottom = async () => {
    await nextTick();
    if (scrollRef.value) {
      const scrollHeight = scrollRef.value?.wrapRef?.scrollHeight || 0;
      const threshold = 100;
      const distanceToBottom =
        scrollHeight -
        scrollRef.value?.wrapRef?.scrollTop! -
        scrollRef.value?.wrapRef?.clientHeight!;
      console.log(distanceToBottom);
      if (distanceToBottom <= threshold) {
        console.log(scrollHeight, "触发滚动");
        scrollRef.value.setScrollTop(scrollHeight);
      }
    }
  };

  return {
    scrollRef,
    scrollToBottom,
    scrollTop,
    scrollToBottomIfAtBottom,
  };
}
